<template>
  <div class="page page-chat-index p-5">
    <div class="chat-hd">
      <div class="logo h-6 w-full mt-5 mb-5">
      </div>
    </div>
    <div class="appscon mb-5">
      <div class="appscon-hd ">
        <span class="favor">
          我的收藏
        </span>
      </div>
      <div class="appscon-bd flex flex-wrap">
        <div class="app" v-for="(app, index) in favorApps">
          <div class="icon m-r-2">
            <img :src="app.poster" alt="" style="width: 38px; height: 38px;;" @click="goApp(app)" />
          </div>
          <div class="name" @click="goApp(app)">
            {{ app.name }}
          </div>
          <div class="btn-favor" :class="[{ isFavor: app.isFavor }]" @click.prevent="toggleFavor(app)"
            v-if="index != 0">

          </div>
        </div>
      </div>
    </div>

    <div class="tabs">
      <div class="tab" :class="[{ active: currentTab == '热门推荐' }]" href="#recommend"
        @click.prevent="scrollTo('recommend', '热门推荐')">
        热门推荐
      </div>
      <div class="tab" :class="[{ active: currentTab == item }]" v-for="(item, index) in labelsGroup"
        :href="'#index' + index" @click.prevent="scrollTo(index, item)">
        {{ item }}
      </div>
    </div>

    <div class="appscon" id="recommend">
      <div class="appscon-hd">
        热门推荐
      </div>
      <div class="appscon-bd flex flex-wrap">
        <div class="app" v-for="(app, index) in recommendList">
          <div class="icon  m-r-2">
            <img :src="app.poster" alt="" style="width: 38px; height: 38px;;" @click="goApp(app)" />
          </div>
          <div class="name " @click="goApp(app)">
            {{ app.name }}
          </div>
          <div class="btn-favor" :class="[{ isFavor: app.isFavor }]" @click.prevent="toggleFavor(app)">

          </div>
        </div>
      </div>
    </div>

    <div class="appscon" v-for="(group, index) in transGroup" :key="index" :id="group.id">
      <div class="appscon-hd">
        {{ group.label }}
      </div>
      <div class="appscon-bd flex flex-wrap">
        <div class="app" v-for="(app, index) in group.apps">
          <div class="icon m-r-2">
            <img :src="app.poster" alt="" style="width: 38px; height: 38px;;" @click="goApp(app)" />
          </div>
          <div class="name" @click="goApp(app)">
            {{ app.name }}
          </div>
          <div class="btn-favor" :class="[{ isFavor: app.isFavor }]" @click.prevent="toggleFavor(app)">

          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
  import { postAIDifyChatApps } from '../../service/yapi';
  const {
    signIn,
    token,
    data: userInfo,
    status,
    lastRefreshedAt,
    signOut,
    getSession,
  } = useAuth();
  import { useAppStore } from "~/stores/app";

  // 使用App Store
  let app = useAppStore();
  let { refreshBalance, downloadByUrl, toggleLoginModal } = app;
  let currentTab = ref('热门推荐');

  // 标签分组
  const labelsGroup = ['学科学习', '非学科学习', '日常生活', '工作效率', '趣味应用'];

  // 在客户端保存的收藏ID
  let favorsId = ref([]);

  // 在服务器端获取所有应用数据
  const { data: allAppsData } = await useAsyncData('allApps', async () => {
    const res = await postAIDifyChatApps({});
    return res.code === 1000 ? res.data : [];
  });

  // 在服务器端获取推荐应用数据
  const { data: recommendAppsData } = await useAsyncData('recommendApps', async () => {
    const res = await postAIDifyChatApps({ isRecommend: 1 });
    return res.code === 1000 ? res.data : [];
  });

  // 所有应用列表
  const AllAppList = computed(() => {
    return allAppsData.value || [];
  });

  // 推荐应用列表，结合客户端收藏状态
  const recommendList = computed(() => {
    return (recommendAppsData.value || []).map(app => {
      return {
        ...app,
        isFavor: favorsId.value.includes(app.id)
      };
    });
  });

  // 收藏应用列表
  const favorApps = computed(() => {
    // 默认"直接聊天"应用
    const defaultApp = {
      "id": 68,
      "name": "直接聊天",
      "intro": null,
      "isRecommend": 1,
      "poster": "https://cdn.codinghou.cn/coding/pc-ai/icons/chat-icon4.png",
      "labels": "非学科学习",
      "appUrl": "https://dify.nongmokeji.com/chatbot/NEh32WnWzuYtJGPj"
    };

    // 筛选收藏应用并排序
    const favoriteApps = AllAppList.value
      .filter(app => favorsId.value.includes(app.id))
      .sort((a, b) => favorsId.value.indexOf(a.id) - favorsId.value.indexOf(b.id))
      .map(app => ({
        ...app,
        isFavor: true
      }));

    return [defaultApp, ...favoriteApps];
  });

  // 按标签分组的应用
  const transGroup = computed(() => {
    return labelsGroup.map((item, index) => {
      return {
        id: `index${index}`,
        label: item,
        value: item,
        apps: AllAppList.value
          .filter(app => app.labels?.split(',').includes(item))
          .map(app => ({
            ...app,
            isFavor: favorsId.value.includes(app.id)
          }))
      };
    });
  });

  // 滚动到指定位置的函数
  const scrollTo = (index, label) => {
    currentTab.value = label;
    let id = `index${index}`;
    if (index === 'recommend') {
      id = 'recommend';
    }
    const element = document.getElementById(id);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' });
    }
  };

  // 处理应用点击，导航到对应页面
  const router = useRouter();
  const goApp = (app) => {
    if (!token.value) {
      toggleLoginModal();
      return ElMessage.warning('请先登录');
    }

    if (app.openType == 'form') {
      let routeUrl = router.resolve({
        path: "/chat/detail/" + app.id,
      });
      window.open(routeUrl.href, '_blank');
    } else {
      let routeUrl = router.resolve({
        path: "/chat/difyApp",
        query: {
          url: encodeURIComponent(app.appUrl)
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  };

  // 切换收藏状态
  const toggleFavor = (app) => {
    let index = favorsId.value.indexOf(app.id);
    if (index > -1) {
      favorsId.value.splice(index, 1);
    } else {
      favorsId.value.push(app.id);
    }
    window.localStorage.setItem('favorsId', JSON.stringify(favorsId.value));
  };

  // 客户端加载完成后处理本地收藏数据
  onMounted(() => {
    let localFavors = window.localStorage.getItem('favorsId');
    if (localFavors) {
      favorsId.value = JSON.parse(localFavors);
    }
  });

  // 页面元数据
  definePageMeta({ auth: false });
</script>

<style lang="scss">
  .page-chat-index {
    .chat-hd {
      .logo {
        height: 24px;
        background: url('https://cdn.codinghou.cn/coding/pc-ai/icons/chat-icon1.png') no-repeat center center;
        background-size: contain;
      }
    }

    .tabs {
      position: -webkit-sticky;
      /* Safari */
      position: sticky;
      top: 0;
      background: #fff;
      z-index: 1000;
      /* 确保 tabs 在其他内容之上 */
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      /* 可选：添加阴影效果 */
      @apply bg-white flex px-10 py-4;

      .tab {
        @apply mx-8 px-4 py-2 cursor-pointer;
        border-radius: 19px;


        &.active {

          background: #D8E2FD;
        }
      }
    }

    .appscon {
      .appscon-hd {
        font-size: 16px;

        .favor {
          padding-right: 20px;
          background: url('https://cdn.codinghou.cn/coding/pc-ai/icons/chat-icon2.png') no-repeat right center;
          background-size: contain;
        }

        @apply py-4 px-2;
      }

      .appscon-bd {

        .app {
          font-size: 16px;

          @apply flex mx-2 my-2 items-center px-4 py-2 bg-white rounded-lg shadow-md pr-8 relative;

          .icon,
          .name {
            cursor: pointer;
          }

          .name {
            cursor: pointer;
            width: 6em;
            /* 设置宽度约为6个字符 */
            overflow: hidden;
            /* 隐藏溢出部分 */
            text-overflow: ellipsis;
            /* 溢出时显示省略号 */
            white-space: nowrap;
            /* 防止文本换行 */
            text-align: left;
            /* 文本左对齐，可以根据需要调整为 center */
            display: inline-block;
            /* 使宽度生效 */
            vertical-align: middle;
            /* 垂直居中对齐（如果需要） */
          }

          .btn-favor {
            position: absolute;

            @apply absolute right-2 top-2 w-4 h-4 cursor-pointer;
            background: url('https://cdn.codinghou.cn/coding/pc-ai/icons/chat-icon3-gray.png') no-repeat center center;
            background-size: contain;

            &.isFavor {
              background: url('https://cdn.codinghou.cn/coding/pc-ai/icons/chat-icon3.png') no-repeat center center;
              background-size: contain;
            }
          }
        }
      }

    }

  }
</style>